﻿//code by Heskey0
//https://space.bilibili.com/455965619
//https://github.com/Heskey0

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Text;

namespace Teresa.Editor
{
    public class UIPanelCodeGen
    {
        private static string _template = @"using System;
using UnityEngine;
using UnityEngine.UI;

namespace Teresa
{
    public class //panel_name : EventBehaviour
    {
        //define_ui
        
        private void Start()
        {
            //init_ui
            
            //注册event
        }

        public override void ProcessMsg(Enum eventCode, object message)
        {
            switch (eventCode)
            {
                //process_msg
                
                default:
                    break;
            }
        }
    }
}";
        
        [MenuItem("CustomTools/UI/GenerateCode/生成Panel代码 %g", priority = 101)]
        public static void PanelCodeGen()
        {
            if (!Selection.activeTransform)
            {
                DebugTools.Log("未选中Panel", "red");
                
                return;
            }
            
            GenerateCode();
        }
        
        public static void GenerateCode()
        {
            var root = Selection.activeTransform.gameObject;
            
            var uiTypeDic = new Dictionary<string, string>();
        
            uiTypeDic.Add("img_", "Image");
            uiTypeDic.Add("btn_", "Button");
            uiTypeDic.Add("txt_", "Text");
            uiTypeDic.Add("if_", "InputField");
            uiTypeDic.Add("sld_", "Slider");
            
            //生成Panel代码
            StringBuilder sb_define = new StringBuilder("");
            StringBuilder sb_init = new StringBuilder("");
            string genCode = string.Copy(_template);
            for (int i = 0; i < root.transform.childCount; i++)
            {
                var childName = root.transform.GetChild(i).name;    //btn_start
                var uiTypeName = childName.Substring(0, childName.IndexOf("_") + 1);    //btn_
                if (childName[0] == '#')
                {
                    continue;
                }
                if (!uiTypeDic.ContainsKey(uiTypeName))
                {
                    DebugTools.Log(childName + "的命名不符合规范", "red");
                    continue;
                }

                sb_define.Append("private ")          //private
                    .Append(uiTypeDic[uiTypeName])    //Button
                    .Append(" ")                      // 
                    .Append(childName)                //btn_start
                    .Append(";\n\t");                 //;

                sb_init.Append(childName) //btn_start
                    .Append(" = ") // = 
                    .Append("transform.Find(\"") //transform.Find("
                    .Append(childName) //btn_start
                    .Append("\")") //")
                    .Append(".GetComponent<").Append(uiTypeDic[uiTypeName]).Append(">();\n\t");
            }

            genCode = genCode.Replace("//panel_name", root.name);

            genCode = genCode.Replace("//define_ui", sb_define.ToString());

            genCode = genCode.Replace("//init_ui", sb_init.ToString());
            
            

            using (FileStream fs = File.Create(AppConfig.Path.UI.UIScriptsPath + "/" + root.name +".cs"))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(genCode);
                    sw.Flush();
                }
            }

            PrefabUtility.SaveAsPrefabAsset(root, AppConfig.Path.UI.UIPrefabPath + "/" + root.name + ".prefab");

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }


        [InitializeOnLoadMethod]
        private static void StartInitializeOnLoadMethod()
        {
            EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
        }

        private static void OnHierarchyGUI(int _, Rect selectionRect)
        {
            if (Event.current != null && Event.current.button == 2 && Event.current.type <= EventType.MouseUp)
            {
                if (Selection.activeTransform)
                {
                    Vector2 mousePosition = Event.current.mousePosition;
                    EditorUtility.DisplayPopupMenu(new Rect(mousePosition.x, mousePosition.y, 0, 0), "CustomTools/UI/GenerateCode/", null);
                }
            }
        }
        
        
        
        
        
        [InitializeOnLoadMethod]
        static void CustomEditor()
        {
            SceneView.duringSceneGui += sceneView =>
            {
                if (Event.current != null
                    && Event.current.keyCode == KeyCode.A
                    && Event.current.type == EventType.KeyDown
                )
                {
                    // Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y - 100, 100,
                    //     100); //根坐标，长，宽
                    //
                    //
                    // Event.current.Use();
                    DebugTools.Log("<color=orange>key A Down</color> in SceneView");
                }

            };
        }
    }
}